package com.bilibili.movies.filter;

import com.bilibili.movies.util.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

import com.alibaba.fastjson.JSON;



@WebFilter("/**")
public class UseFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        String requestURL = request.getRequestURI();
        if(requestURL.contains("/login")||requestURL.contains("/register")||requestURL.contains("/getEmailCode")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("token");
        System.out.println("This token=="+token);

        if(token!=null){

            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 Unauthorized
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }
}
